package com.ruoyi.service.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.archive.domain.ArchivePerson;
import com.ruoyi.archive.mapper.ArchivePersonMapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.service.mapper.ServicePetMapper;
import com.ruoyi.service.domain.ServicePet;
import com.ruoyi.service.service.IServicePetService;

/**
 * 宠物信息Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-04-21
 */
@Service
public class ServicePetServiceImpl implements IServicePetService 
{
    private static final Logger log = LoggerFactory.getLogger(ServicePetServiceImpl.class);

    @Autowired
    private ServicePetMapper servicePetMapper;
    @Autowired
    private ArchivePersonMapper archivePersonMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询宠物信息
     * 
     * @param id 宠物信息主键
     * @return 宠物信息
     */
    @Override
    public ServicePet selectServicePetById(Long id)
    {
        return servicePetMapper.selectServicePetById(id);
    }

    /**
     * 查询宠物信息列表
     * 
     * @param servicePet 宠物信息
     * @return 宠物信息
     */
    @Override
    public List<ServicePet> selectServicePetList(ServicePet servicePet)
    {
        return servicePetMapper.selectServicePetList(servicePet);
    }

    /**
     * 新增宠物信息
     * 
     * @param servicePet 宠物信息
     * @return 结果
     */
    @Override
    public int insertServicePet(ServicePet servicePet)
    {
        servicePet.setCreateTime(DateUtils.getNowDate());
        return servicePetMapper.insertServicePet(servicePet);
    }

    /**
     * 修改宠物信息
     * 
     * @param servicePet 宠物信息
     * @return 结果
     */
    @Override
    public int updateServicePet(ServicePet servicePet)
    {
        servicePet.setUpdateTime(DateUtils.getNowDate());
        return servicePetMapper.updateServicePet(servicePet);
    }

    /**
     * 批量删除宠物信息
     * 
     * @param ids 需要删除的宠物信息主键
     * @return 结果
     */
    @Override
    public int deleteServicePetByIds(Long[] ids)
    {
        return servicePetMapper.deleteServicePetByIds(ids);
    }

    /**
     * 删除宠物信息信息
     * 
     * @param id 宠物信息主键
     * @return 结果
     */
    @Override
    public int deleteServicePetById(Long id)
    {
        return servicePetMapper.deleteServicePetById(id);
    }


    /**
   * 导入数据
   *
   * @param dataList 数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName 操作用户
   * @return 结果
   */
    @Override
    public String importData(List<ServicePet> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        SysDept dc = new SysDept();
        dc.setDelFlag("0");
        dc.setDeptType("community");;
        List<SysDept> deptList = sysDeptMapper.selectDeptList(dc);
        if(deptList == null || deptList.isEmpty()){
            throw new ServiceException("请先添加区域信息");
        }

        Map<String, Long> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptId));

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ServicePet row : dataList)
        {
            try
            {

                if(StringUtils.isEmpty(row.getDeptName())){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、宠物 " + row.getPermit() + "、的区域信息不能为空");
                    continue;
                }
                Long deptId = deptMap.get(row.getDeptName().trim());
                if(deptId == null){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、区域 " + row.getDeptName() + " 不存在");
                    continue;
                }
                row.setDeptId(deptId);

                if(StringUtils.isNotEmpty(row.getPersonCard())) {
                    ArchivePerson archivePerson = archivePersonMapper.selectArchivePersonByCard(row.getPersonCard());
                    if(archivePerson == null){
                        throw new ServiceException("业主不存在，请先添加业主信息:"+row.getPersonCard());
                    }
                    row.setPersonId(archivePerson.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum+ "、宠物 " + row.getPermit() + "、业主身份证不能为空");
                    continue;
                }

                BeanValidators.validateWithException(validator, row);
                ServicePet old = servicePetMapper.selectServicePetByPermit(row.getPermit());
                if(old == null) {
                    row.setCreateBy(operName);
                    row.setCreateTime(new Date());
                    insertServicePet(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、宠物 " + row.getPermit() + " 导入成功");
                }else if(isUpdateSupport){
                    row.setId(old.getId());
                    row.setUpdateBy(operName);
                    row.setUpdateTime(new Date());
                    successMsg.append("<br/>" + successNum + "、宠物 " + row.getPermit() + " 更新成功");
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、宠物 " + row.getPermit() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、宠物 " + row.getPermit() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
